from zope.interface import implements

from twisted.plugin import IPlugin
from twisted.internet import defer

from pyhnode import interfaces, config

import os, time

class AlternativePlugin:
    """Plugin for using alternative measuring modules (in this case, Munin
    plugins)."""

    implements(IPlugin, interfaces.IPlugins)

    def __init__(self):
        self.plugins = {}

    def getNames(self):
        return self.plugins.keys()

    def configure(self):
        self.basedir = config.conf.get('plugins', 'scriptdir')
        for i in os.listdir(self.basedir):
            self.plugins[i] = ""
        for i in config.conf.get('plugins', 'simple').split(',') +\
            config.conf.get('plugins', 'buffered').split(','):
            if self.plugins.has_key(i):
                self.plugins[i] = config.conf.get(i, 'interpreter')

    def getValueFromScript(self, plug):
        origdir = os.getcwd()
        os.chdir(self.basedir)
        ret = os.popen(self.plugins[plug] + " " + plug).read()
        os.chdir(origdir)
        vals = {}
        for i in ret[:-1].split('\n'):
            e = i.split(' ')
            vals[e[0].split('.')[0]] = e[1]

        return [str(int(time.time())), vals]

    def getValue(self, plug):
        return defer.succeed(self.getValueFromScript(plug))

    def getAlert(self, plug):
        pass

    def getConfig(self, plug):
        origdir = os.getcwd()
        os.chdir(self.basedir)
        ret = os.popen(self.plugins[plug] + " " + plug +\
                       " config").read().split('\n')
        cf = {}
        gr = {}
        for i in ret:
            k = i.split(' ')
            if len(k[0].split('.')) > 1:
                cf[k[0].split('.')[0]] = {}
        for i in ret:
            sep = '@'
            k = i.split(' ')
            if len(k[0].split('.')) > 1:
                cf[k[0].split('.')[0]][".".join(k[0].split('.')[1:])] =\
                  sep.join(k[1:]) 
            elif len(k[0].split('.')) == 1:
                gr[k[0].split('.')[0]] = sep.join(k[1:]) 
        conf = ";title:" + gr['graph_title']
        for i in cf.keys():
            conf += "|" + i + "#label:" + cf[i]['label']
            if cf[i].has_key('type'):
                conf += ";stype:" + cf[i]['type']
            else:
                conf += ";stype:GAUGE"
            if cf[i].has_key('cdef'):
                conf += ";cdef:" + cf[i]['cdef']
            if cf[i].has_key('draw'):
                conf += ";draw:" + cf[i]['draw']
        
        return conf

ap = AlternativePlugin()

